import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;

public class LinkGetter extends HTMLEditorKit.ParserCallback {
	private String baseURL;
	private Spider list;

	public LinkGetter(Spider list) {
		this.list = list;
	}

	public void handleStartTag(HTML.Tag tag, MutableAttributeSet a, int position) {
		if (tag == HTML.Tag.A) {
			String href = (String) a.getAttribute(HTML.Attribute.HREF);
			try {
				URL url;
				if (!new URI(href).isAbsolute()) {
					url = new URL(new URL(baseURL), href);
				} else {
					url = new URL(href);
				}
				list.addLink(url);
			} catch (Exception e) {
			}

		}
		if (tag == HTML.Tag.FRAME) {
			String href = (String) a.getAttribute(HTML.Attribute.SRC);
			URL url;
			try {
				url = new URL(href);
				list.addLink(url);
			} catch (MalformedURLException e) {
			}
		}

	}

	public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
		if (t == HTML.Tag.BASE) {
			String href = (String) a.getAttribute(HTML.Attribute.HREF);
			baseURL = href;
			try {
				URL url = new URL(href);
				list.addLink(url);
			} catch (MalformedURLException e) {
			}
		}
	}

}
